<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="./ajax.js"></script>
  <script>

    // 1. 被async关键字修饰的函数，它的返回值默认都会被promise包裹一层
    // 2. await 等待 等待一个promise（承诺），这个promise什么时候来，不知道，是异步的，它必须和被async修饰的函数连用，不能单独使用
    // 被await修饰的这些异步，就像同步一样执行
    // async function normal() {
    //   return 1
    // }
    // let res = normal()
    // console.log(res);

    async function getData() {
      let res = await axios.get('http://localhost:3000/books')
      // console.log(res);
    }
    getData()

    function getArticle() {
      return new Promise((resolve, reject) => {
        myajax({
          type: 'GET',
          url: 'http://192.168.14.86:3000/article',
          data: {},
          success: function (res) {
            resolve(JSON.parse(res))
          }
        })
      })
    }
    function getUserDetail(article) {
      return new Promise((resolve, reject) => {
        myajax({
          type: 'GET',
          url: 'http://192.168.14.86:3000/author/' + article.authorId,
          data: {},
          success: function (res) {
            resolve(JSON.parse(res))
          }
        })
      })
    }
    function getAddressDetail(userDetail) {
      return new Promise((resolve, reject) => {
        myajax({
          type: 'GET',
          url: 'http://192.168.14.86:3000/address/' + userDetail.birthPlace,
          data: {},
          success: function (res) {
            resolve(JSON.parse(res))
          }
        })
      })
    }

    async function getData2() {
      try {
        // console.log(bbbb); // 这个错误会被catch捕获到
        let article = await getArticle()
        let user = await getUserDetail(article)
        let city = await getAddressDetail(user)
        console.log(city);
      } catch (error) {
        console.log(error);
      }
    }
    getData2()





    function sto1() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('1111')
        }, 3000)
      })
    }
    function sto2() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('2222')
        }, 1000)
      })
    }

    async function getData3() {
      let str1 = await sto1()
      console.log(str1);
      let str2 = await sto2()
      console.log(str2);
    }
    getData3()
  </script>
</body>

</html>